<!doctype html>
<html class="theme-next use-motion theme-next-mist">
<head>
  
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

  <meta name="google-site-verification" content="K8DCBviaoTBKVs28YBB7IBIbospQ9RVlgSh81RYMUhY" />


  <meta name="baidu-site-verification" content="tXr3ZTm3Hx" />



  <link rel="stylesheet" type="text/css" href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5"/>


<link rel="stylesheet" type="text/css" href="/css/main.css?v=0.4.5.1"/>

  <meta name="description" content="xgfe's blog. 鲜果前端的技术博客，鲜果前端研发部官方博客。前端基础技术研究：html, html5, javascript, css, css3；前端框架研究：angularJs, react, react native." />


  <meta name="keywords" content="Vue2.0,Vue-resource,Express," />


  <link rel="alternate" target="_blank" href="/atom.xml" title="xgfe" type="application/atom+xml" />


  <link rel="shorticon icon" type="image/x-icon" href="http://p0.meituan.net/xgfe/2db359f56ce13be30dedef160e0e57ce16958.ico?v=0.4.5.1" />

<meta name="description" content="前言继上一篇文章Vue2.0+Vue-router2.0+Vuex2.0搭建简书，该文章主要讲述简书网站的前端搭建过程。本篇文章将重点讲述简书网站的服务端搭建，服务端主要通过Express启动一个本地server处理请求，将数据保存至数据库中。">
<meta name="keywords" content="Vue2.0,Vue-resource,Express">
<meta property="og:type" content="article">
<meta property="og:title" content="Vue2.0+Vue-resource+Express搭建简书网站服务端">
<meta property="og:url" content="http://xgfe.github.io/2017/03/02/zhouxiong/Vue2.0+Vue-resource+Express-Server/index.html">
<meta property="og:site_name" content="xgfe">
<meta property="og:description" content="前言继上一篇文章Vue2.0+Vue-router2.0+Vuex2.0搭建简书，该文章主要讲述简书网站的前端搭建过程。本篇文章将重点讲述简书网站的服务端搭建，服务端主要通过Express启动一个本地server处理请求，将数据保存至数据库中。">
<meta property="og:image" content="https://p0.meituan.net/dpnewvc/40aff5f1eb64935fd76a4f98f87a81e6125260.png">
<meta property="og:image" content="https://p1.meituan.net/dpnewvc/c37d4ffb5dfd48d02965834c22bf086d99843.png">
<meta property="og:image" content="https://p0.meituan.net/dpnewvc/16943ad2e51e5b7f9b8cd159c5cb9dbd1472821.png">
<meta property="og:updated_time" content="2017-04-12T08:03:36.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Vue2.0+Vue-resource+Express搭建简书网站服务端">
<meta name="twitter:description" content="前言继上一篇文章Vue2.0+Vue-router2.0+Vuex2.0搭建简书，该文章主要讲述简书网站的前端搭建过程。本篇文章将重点讲述简书网站的服务端搭建，服务端主要通过Express启动一个本地server处理请求，将数据保存至数据库中。">
<meta name="twitter:image" content="https://p0.meituan.net/dpnewvc/40aff5f1eb64935fd76a4f98f87a81e6125260.png">


<script type="text/javascript" id="hexo.configuration">
  var CONFIG = {
    scheme: 'Mist',
    sidebar: 'post'
  };
</script>

  <title> Vue2.0+Vue-resource+Express搭建简书网站服务端 | xgfe </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
  <div style="position: fixed; top: -9999px; left: -9999px;">
    <img src="http://p0.meituan.net/xgfe/082a9624ba5ae8602150a2d43968463e49348.png" alt="xgfe"/>
  </div>
  <!--[if lte IE 8]>
  <div style=' clear: both; height: 59px; padding:0 0 0 15px; position: relative;margin:0 auto;'>
    <a href="http://windows.microsoft.com/en-US/internet-explorer/products/ie/home?ocid=ie6_countdown_bannercode">
      <img src="http://7u2nvr.com1.z0.glb.clouddn.com/picouterie.jpg" border="0" height="42" width="820"
           alt="You are using an outdated browser. For a faster, safer browsing experience, upgrade for free today or use other browser ,like chrome firefox safari."
           style='margin-left:auto;margin-right:auto;display: block;'/>
    </a>
  </div>
<![endif]-->
  

  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?3601d4483819a5ab6ddabb0b6422a328";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>



  <div class="container one-column page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><h1 class="site-meta">
  <span class="logo-line-before"><i></i></span>
  <a href="/" class="brand" rel="start">
      <span class="logo">
        <i class="icon-next-logo"></i>
      </span>
      <span class="site-title">xgfe</span>
  </a>
  <span class="logo-line-after"><i></i></span>
</h1>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  
  

  
    <ul id="menu" class="menu menu-left">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            <i class="menu-item-icon icon-next-home"></i> <br />
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            <i class="menu-item-icon icon-next-archives"></i> <br />
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            <i class="menu-item-icon icon-next-tags"></i> <br />
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-join">
          <a href="/join" rel="section">
            <i class="menu-item-icon icon-next-join"></i> <br />
            加入我们
          </a>
        </li>
      
      <!-- slide-links added by felix -->
      <li class="menu-item menu-item-slides" style="opacity: 1; transform: translateY(0px);">
        <a href="http://xgfe.github.io/Basics/" target="_blank" rel="section">
          <i class="menu-item-icon icon-next-slides"></i> <br>
          Basics
        </a>
      </li>
      <li class="menu-item menu-item-slides" style="opacity: 1; transform: translateY(0px);">
        <a href="https://slides.com/xgfe" target="_blank" rel="section">
          <i class="menu-item-icon icon-next-slides"></i> <br>
          Slides
        </a>
      </li>

      
      
    </ul>
  

  
    <div class="site-search">
      

    </div>
  

    <div class="site-search">
      <form class="site-search-form" id="gg-form" action="https://www.google.com/webhp" >
        <input type="text" name="q" id="gg-search-input" class="menu-search-input">
      </form>
    </div>
</nav>
 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div id="content" class="content"> 

  <div id="posts" class="posts-expand">
    

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <header class="post-header">

      
      
        <h1 class="post-title" itemprop="name headline">
          
          
            
              Vue2.0+Vue-resource+Express搭建简书网站服务端
            
          
        </h1>
      

      <div class="post-meta">
        <span class="post-time">
          发表于
          <time itemprop="dateCreated" datetime="2017-03-02T00:00:00+08:00" content="2017-03-02">
            2017-03-02
          </time>
        </span>

        
          <span class="post-category" >
            &nbsp; | &nbsp; 作者
            
              <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                <a href="/categories/zhouxiong/" itemprop="url" rel="index">
                  <span itemprop="name">zhouxiong</span>
                </a>
              </span>

              
              

            
          </span>
        

        
          
        

        <!-- tags 挪动位置 -->
        
          <span class="post-tags">
            &nbsp; | &nbsp;
            
              <a href="/tags/Vue2-0/" rel="tag"><i class="icon-next-tags"></i>Vue2.0</a>
            
              <a href="/tags/Vue-resource/" rel="tag"><i class="icon-next-tags"></i>Vue-resource</a>
            
              <a href="/tags/Express/" rel="tag"><i class="icon-next-tags"></i>Express</a>
            
          </span>
        
      </div>
    </header>

    <div class="post-body">

      
      

      
        <span itemprop="articleBody"><h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>继上一篇文章<a href="http://xgfe.github.io/2016/12/22/zhouxiong/Vue2.0+Vue-router2.0+Vuex2.0/">Vue2.0+Vue-router2.0+Vuex2.0搭建简书</a>，该文章主要讲述简书网站的前端搭建过程。本篇文章将重点讲述简书网站的服务端搭建，服务端主要通过Express启动一个本地server处理请求，将数据保存至数据库中。</p>
<a id="more"></a>
<p><strong>注意：本篇文章只介绍了比较重要的几个文件的内容，有些文件内容类似就没有拿出来讲解。所以代码并不是全部的，所以按照本文的内容并不能完全搭建起一个网站，想要全部的代码可以从下面的github仓库中获取</strong></p>
<p>github地址：<a href="https://github.com/zhouxiongking/vue2.0-vuex2.0-demo-jianshu" target="_blank" rel="external">https://github.com/zhouxiongking/vue2.0-vuex2.0-demo-jianshu</a></p>
<h3 id="准备知识"><a href="#准备知识" class="headerlink" title="准备知识"></a>准备知识</h3><ul>
<li><p>vue-resource</p>
<p>vue-resouce是一款Vue.js插件，他可以通过XMLHttpRequest或JSONP发起请求并处理响应，也就是说$.ajax能做的事情，vue-resource插件也能够做到，而且vue-resource的API更为简洁。</p>
</li>
<li><p>Express</p>
<p>Express是基于Node.js的Web开发框架，可以快速地搭建一个完整功能的网站</p>
</li>
<li><p>数据库知识</p>
<p>基本的数据库知识，包括表的创建，增删改查等操作，会编写SQL语句 </p>
</li>
</ul>
<h3 id="数据库设计"><a href="#数据库设计" class="headerlink" title="数据库设计"></a>数据库设计</h3><p>简书网站主要分为用户表和文章表，因此数据库设计如下，建表语句对应的文件为jianshu.sql</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div></pre></td><td class="code"><pre><div class="line">create table users</div><div class="line">(</div><div class="line">   id                   int          auto_increment    not null primary key,</div><div class="line">   email                varchar(50)                    not null,</div><div class="line">   nickname             varchar(15)                    not null,</div><div class="line">   telephone            varchar(11)                    null,</div><div class="line">   password             varchar(20)                    not null,</div><div class="line">   attention_count      int          default 0         null,</div><div class="line">   enjoy_count          int          default 0         null</div><div class="line">)ENGINE=InnoDB DEFAULT CHARSET=utf8;</div><div class="line"></div><div class="line">create table article</div><div class="line">(</div><div class="line">  id                   int          auto_increment    not null primary key,</div><div class="line">  type                 varchar(10)                    null,</div><div class="line">  topic                varchar(10)                    null,</div><div class="line">  user_id              int                            not null,</div><div class="line">  title                varchar(30)                    not null,</div><div class="line">  content              longtext                       not null,</div><div class="line">  read_count           int          default 0         null,</div><div class="line">  comment_count        int          default 0         null,</div><div class="line">  like_count           int          default 0         null,</div><div class="line">  reward_count         int          default 0         null,</div><div class="line">  publish_time         varchar(20)                    null,</div><div class="line">  picture_url          varchar(100)                   null</div><div class="line">)ENGINE=InnoDB DEFAULT CHARSET=utf8;</div></pre></td></tr></table></figure>
<h3 id="创建server"><a href="#创建server" class="headerlink" title="创建server"></a>创建server</h3><p>在build/dev-server.js文件中可以发现有以下代码</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">var express = require(&apos;express&apos;);</div><div class="line">var app = express();</div></pre></td></tr></table></figure>
<p>该代码表示利用Express启动一个server，而且通过<code>app.use()</code>方法使用了一系列的中间件，在实现对应的模块功能时会添加对应的处理。</p>
<p>为了方便做更好的讲解，下面将通过实际的功能模块进行描述，主要包括注册登录模块和编写文章模块以及加载文章列表模块三个部分。</p>
<h3 id="注册与登录"><a href="#注册与登录" class="headerlink" title="注册与登录"></a>注册与登录</h3><p>首先看下登录的页面<br><img src="https://p0.meituan.net/dpnewvc/40aff5f1eb64935fd76a4f98f87a81e6125260.png" alt="登录界面"></p>
<p>注册与登录主要是针对用户的操作，我们按照这个功能的整个流程来讲解。</p>
<ul>
<li><p>前端页面的编写</p>
</li>
<li><p>利用vue-resource发送请求到后端</p>
</li>
<li><p>服务端接收请求，处理参数</p>
</li>
<li><p>处理完的数据存入数据库</p>
</li>
<li><p>给前端页面响应的响应结果</p>
</li>
</ul>
<h4 id="前端页面内容"><a href="#前端页面内容" class="headerlink" title="前端页面内容"></a>前端页面内容</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line">&lt;form name=&quot;formLogin&quot; class=&quot;login-form&quot; accept-charset=&quot;UTF-8&quot; method=&quot;post&quot;&gt;</div><div class="line">  &lt;div class=&quot;username&quot;&gt;</div><div class="line">    &lt;span class=&quot;span1&quot;&gt;&lt;i class=&quot;fa fa-user&quot;&gt;&lt;/i&gt;&lt;/span&gt;</div><div class="line">    &lt;input type=&quot;text&quot; name=&quot;login_name&quot; placeholder=&quot;邮件/电话号码&quot; v-model=&quot;login.email&quot; class=&quot;span2&quot;&gt;</div><div class="line">  &lt;/div&gt;</div><div class="line">  &lt;div class=&quot;password&quot;&gt;</div><div class="line">    &lt;span class=&quot;span1&quot;&gt;&lt;i class=&quot;fa fa-unlock-alt&quot;&gt;&lt;/i&gt;&lt;/span&gt;</div><div class="line">    &lt;input type=&quot;password&quot; name=&quot;login_password&quot; placeholder=&quot;密码&quot; v-model=&quot;login.password&quot; class=&quot;span2&quot;&gt;</div><div class="line">  &lt;/div&gt;</div><div class="line">  &lt;button class=&quot;login-btn btn&quot; type=&quot;button&quot; @click=&apos;doLogin&apos;&gt;&lt;span&gt;登录&lt;/span&gt;&lt;/button&gt;</div><div class="line">  &lt;div class=&quot;login-control&quot;&gt;</div><div class="line">			&lt;span class=&quot;f-l checkbox&quot; :class=&quot;&#123;checked: checked === true&#125;&quot;</div><div class="line">        @click=&quot;checked = !checked&quot;&gt;</div><div class="line">				&lt;input type=&quot;checkbox&quot; class=&quot;remember&quot; checked=&quot;checked&quot;&gt;</div><div class="line">				&lt;ins class=&quot;check&quot;&gt;&lt;/ins&gt;</div><div class="line">			&lt;/span&gt;</div><div class="line">    &lt;span class=&quot;f-l&quot;&gt;记住我&lt;/span&gt;</div><div class="line">    &lt;span class=&quot;f-r&quot;&gt;&lt;a href=&quot;#&quot; class=&quot;forget-color&quot;&gt;忘记密码&lt;/a&gt;&lt;/span&gt;</div><div class="line">  &lt;/div&gt;</div><div class="line">&lt;/form&gt;</div></pre></td></tr></table></figure>
<h4 id="vue-resource发送请求"><a href="#vue-resource发送请求" class="headerlink" title="vue-resource发送请求"></a>vue-resource发送请求</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"> // 注册</div><div class="line">doRegist () &#123;</div><div class="line">    this.$http.post(&apos;/user/register&apos;, this.user).then(function (response) &#123;</div><div class="line">        this.dealResponse(response)</div><div class="line">    &#125;)</div><div class="line">&#125;,</div><div class="line">// 登陆</div><div class="line">doLogin () &#123;</div><div class="line">    var url = &apos;/user/login?email=&apos; + this.login.email + &apos;&amp;password=&apos; + this.login.password</div><div class="line">    this.$http.get(url).then(function (response) &#123;</div><div class="line">        this.dealResponse(response)</div><div class="line">    &#125;)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h4 id="服务端接收请求"><a href="#服务端接收请求" class="headerlink" title="服务端接收请求"></a>服务端接收请求</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div></pre></td><td class="code"><pre><div class="line">// 用户注册</div><div class="line">app.post(&apos;/user/register&apos;, function (req, res) &#123;</div><div class="line">    var user = req.body   //post请求中，需要通过req.body获取请求体的内容</div><div class="line">    userDbUtil.getUserByRegister(user.email, user.nickname).then(function (response) &#123;</div><div class="line">        if(response[0]) &#123;</div><div class="line">            var respResult = &#123;</div><div class="line">                status: 0,</div><div class="line">                message: &apos;邮箱/电话/昵称已注册,请重新注册!&apos;</div><div class="line">            &#125;</div><div class="line">            appResponse(res, JSON.stringify(respResult))</div><div class="line">        &#125; else &#123;</div><div class="line">            userDbUtil.saveUser(user).then(function () &#123;</div><div class="line">                var respResult = &#123;</div><div class="line">                    status: 1,</div><div class="line">                    message: &apos;恭喜你,注册成功!&apos;</div><div class="line">                &#125;</div><div class="line">                appResponse(res, JSON.stringify(respResult))</div><div class="line">            &#125;)</div><div class="line">        &#125;</div><div class="line">    &#125;, function () &#123;</div><div class="line">        var respResult = &#123;</div><div class="line">            status: 0,</div><div class="line">            message: &apos;注册失败!&apos;</div><div class="line">        &#125;</div><div class="line">        appResponse(res, JSON.stringify(respResult))</div><div class="line">    &#125;)</div><div class="line">&#125;)</div><div class="line"></div><div class="line">// 登陆</div><div class="line">app.get(&apos;/user/login&apos;, function (req, res) &#123;</div><div class="line">    var email = req.query.email    //get请求中，通过req.query属性获取传递的参数</div><div class="line">    var password = req.query.password</div><div class="line">    userDbUtil.getUserByLogin(email, password).then(function (response) &#123;</div><div class="line">        var respResult</div><div class="line">        if(response.length) &#123;</div><div class="line">            // 登录信息写入session</div><div class="line">            req.session.isLogin = true;</div><div class="line">            req.session.user = response[0];</div><div class="line">            respResult = &#123;</div><div class="line">                status: 1,</div><div class="line">                message: &apos;登录成功!&apos;</div><div class="line">            &#125;</div><div class="line">        &#125; else &#123;</div><div class="line">            respResult = &#123;</div><div class="line">                status: 0,</div><div class="line">                message: &apos;用户名或密码错误,登录失败!&apos;</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">        appResponse(res, JSON.stringify(respResult))</div><div class="line">    &#125;, function () &#123;</div><div class="line">        var respResult = &#123;</div><div class="line">            status: 0,</div><div class="line">            message: &apos;用户名或密码错误,登录失败!&apos;</div><div class="line">        &#125;</div><div class="line">        appResponse(res, JSON.stringify(respResult))</div><div class="line">    &#125;)</div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<p>在用户登录的时候会利用session记录登录信息，所以在Express中需要引入<code>express-session</code>模块，在build/dev-server.js文件中需要添加如下代码</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">// 引入session模块,判断登录情况</div><div class="line">var session = require(&apos;express-session&apos;)</div><div class="line">app.use(session(&#123;</div><div class="line">  secret: &apos;kingx_only&apos;,</div><div class="line">  cookie: &#123;maxAge: 20 * 60 * 1000&#125;</div><div class="line">&#125;))</div></pre></td></tr></table></figure>
<h4 id="数据库操作"><a href="#数据库操作" class="headerlink" title="数据库操作"></a>数据库操作</h4><ul>
<li>数据库的连接</li>
</ul>
<p>数据库的连接是通用的操作，所以将其封装在一个文件dbUtil/dbConnection.js中，各个模块需要使用数据库的操作时只需要require该文件即可。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line">var mysql = require(&apos;mysql&apos;)</div><div class="line"></div><div class="line">// 以下的数据库名称，用户名和密码大家自行更改</div><div class="line">var options = &#123;</div><div class="line">    host: &apos;localhost&apos;,</div><div class="line">    port: 3306,</div><div class="line">    user: &apos;root&apos;,</div><div class="line">    password: &apos;XXX&apos;,</div><div class="line">    database: &apos;jianshu&apos;</div><div class="line">&#125;</div><div class="line"></div><div class="line">var connection = mysql.createConnection(options)</div><div class="line"></div><div class="line">module.exports = connection</div></pre></td></tr></table></figure>
<ul>
<li>数据库操作</li>
</ul>
<p>在将数据保存至数据库中时，利用Promise实现</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div></pre></td><td class="code"><pre><div class="line">// 保存用户</div><div class="line">userDbUtil.saveUser = function (user) &#123;</div><div class="line">    var promise = new Promise(function (resolve, reject) &#123;</div><div class="line">        var sql = &apos;insert into users(email, nickname, password) values(?, ?, ?)&apos;</div><div class="line">        var params = [user.email, user.nickname, user.password]</div><div class="line"></div><div class="line">        connection.connect(function()&#123;</div><div class="line">            connection.query(sql, params, function (error, response) &#123;</div><div class="line">                if(error)&#123;</div><div class="line">                    reject(error)</div><div class="line">                &#125; else &#123;</div><div class="line">                    resolve(response)</div><div class="line">                &#125;</div><div class="line">            &#125;)</div><div class="line">        &#125;)</div><div class="line">    &#125;)</div><div class="line">    return promise</div><div class="line">&#125;</div><div class="line"></div><div class="line">// 注册时,查找用户</div><div class="line">userDbUtil.getUserByRegister = function (email, nickname) &#123;</div><div class="line">    var promise = new Promise(function (resolve, reject) &#123;</div><div class="line">        var sql = &apos;select * from users where email = ? or nickname = ?&apos;</div><div class="line">        var params = [email, nickname]</div><div class="line">        connection.connect(function () &#123;</div><div class="line">            connection.query(sql, params, function (error, response) &#123;</div><div class="line">                if(error) &#123;</div><div class="line">                    reject(error)</div><div class="line">                &#125; else &#123;</div><div class="line">                    resolve(response)</div><div class="line">                &#125;</div><div class="line">            &#125;)</div><div class="line">        &#125;)</div><div class="line">    &#125;)</div><div class="line">    return promise</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<ul>
<li>处理响应</li>
</ul>
<p>在前端页面文件中，将处理响应的函数封装成一个公共的函数</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line">// 处理响应</div><div class="line">dealResponse (response) &#123;</div><div class="line">    var self = this</div><div class="line">    self.show_result = true</div><div class="line">    var resData = JSON.parse(response.body)</div><div class="line">    this.result = resData.message</div><div class="line">    if (resData.status) &#123;</div><div class="line">        setTimeout(function () &#123;</div><div class="line">            self.show_result = false</div><div class="line">            // 注册成功后,直接自动登录到主页</div><div class="line">            self.$router.push(&apos;/home/article/hot&apos;)</div><div class="line">            self.$store.dispatch(&apos;changeIsLogin&apos;, true)</div><div class="line">        &#125;, 1000)</div><div class="line">    &#125; else &#123;</div><div class="line">        setTimeout(function () &#123;</div><div class="line">            self.show_result = false</div><div class="line">        &#125;, 1000)</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>通过以上5步，就可以完成用户注册或者登陆的操作，当然上述代码并不是全部的代码，只是一些必要的函数，如果需要整体运行，还需要在本地建立好数据库，然后运行整个系统</p>
<h3 id="写文章"><a href="#写文章" class="headerlink" title="写文章"></a>写文章</h3><p>在完成用户的注册和登录功能后，写文章应该是简书最重要的功能了，同样我们按照上述5个步骤来实现这个功能。首先来看下写文章的界面如下<br><img src="https://p1.meituan.net/dpnewvc/c37d4ffb5dfd48d02965834c22bf086d99843.png"></p>
<h4 id="前端页面内容-1"><a href="#前端页面内容-1" class="headerlink" title="前端页面内容"></a>前端页面内容</h4><p>为了能写出更好看的文章，也是费了一段功夫去找支持vue的富文本编辑器，虽然现在的vue富文本编辑器已经有很多了，但是也会有各种各样的问题，比如使用复杂度上，或者字体上，最终选取了<a href="https://github.com/surmon-china/vue-quill-editor" target="_blank" rel="external">vue-quill-editor</a>作为简书的文本编辑器。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line">&lt;div class=&quot;note-editor&quot;&gt;</div><div class="line">  &lt;div class=&quot;wrapper-head&quot;&gt;</div><div class="line">    &lt;div class=&quot;note-head&quot;&gt;</div><div class="line">      &lt;input type=&quot;text&quot; class=&quot;top-title&quot; data-type=&quot;title&quot; v-model=&quot;note.title&quot;&gt;</div><div class="line">    &lt;/div&gt;</div><div class="line">  &lt;/div&gt;</div><div class="line">  &lt;div class=&quot;wrapper-body&quot;&gt;</div><div class="line"></div><div class="line">    &lt;quill-editor ref=&quot;myTextEditor&quot;</div><div class="line">                  v-model=&quot;note.content&quot;</div><div class="line">                  :config=&quot;editorOption&quot;</div><div class="line">                  @blur=&quot;onEditorBlur($event)&quot;</div><div class="line">                  @focus=&quot;onEditorFocus($event)&quot;</div><div class="line">                  @ready=&quot;onEditorReady($event)&quot;&gt;&lt;/quill-editor&gt;</div><div class="line">  &lt;/div&gt;</div><div class="line">  &lt;div class=&quot;wrapper-footer&quot;&gt;</div><div class="line">    &lt;div class=&quot;footer-div&quot;&gt;</div><div class="line">      &lt;button class=&quot;btn&quot; @click=&quot;saveArticle&quot;&gt;保存&lt;/button&gt;</div><div class="line">    &lt;/div&gt;</div><div class="line">  &lt;/div&gt;</div><div class="line">&lt;/div&gt;</div></pre></td></tr></table></figure>
<h4 id="Vue-resource发送请求"><a href="#Vue-resource发送请求" class="headerlink" title="Vue-resource发送请求"></a>Vue-resource发送请求</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">// 保存文章</div><div class="line">saveArticle () &#123;</div><div class="line">    this.$http.post(&apos;/article/saveArticle&apos;, this.note).then(function (response) &#123;</div><div class="line">    	</div><div class="line">    &#125;)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h4 id="服务端处理请求"><a href="#服务端处理请求" class="headerlink" title="服务端处理请求"></a>服务端处理请求</h4><p>在使用<code>vue-quill-editor</code>富文本编辑器编写文章的时候，如果遇到添加图片的情况，<code>vue-quill-editor</code>会将图片转化为base64格式的编码，由于base64格式编码的数据量会很大，这样在发送请求时Express会报错。因此需要对Express的body-parser模块进行设置。在build/dev-server.js文件下，添加如下代码</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">// 需要使用body-parser模块,要不然post方法获取不到传递的参数</div><div class="line">var bodyParser = require(&apos;body-parser&apos;)</div><div class="line">// 设置接收参数的大小,主要针对于base64的图片</div><div class="line">app.use(bodyParser(&#123;limit: &apos;50mb&apos;&#125;))</div><div class="line">app.use(bodyParser.json())</div><div class="line">app.use(bodyParser.urlencoded(&#123;extended: false&#125;))</div></pre></td></tr></table></figure>
<p>实际处理文章的服务端代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div></pre></td><td class="code"><pre><div class="line">// 保存文章</div><div class="line">app.post(&apos;/article/saveArticle&apos;, function (req, res) &#123;</div><div class="line">    var article = req.body</div><div class="line">    // 获取用户id</div><div class="line">    article.userId = req.session.user.id</div><div class="line">    // 获取当前时间</div><div class="line">    article.publishTime = new Date().format(&apos;yyyy-MM-dd hh:mm:ss&apos;)</div><div class="line">    articleDbUtil.saveArticle(article).then(function (response) &#123;</div><div class="line">        var resultObj = &#123;</div><div class="line">            status: 1,</div><div class="line">            message: &apos;保存成功&apos;,</div><div class="line">            articleId: response[0].id</div><div class="line">        &#125;</div><div class="line">        appResponse(res, JSON.stringify(resultObj))</div><div class="line">    &#125;, function () &#123;</div><div class="line">        var resultObj = &#123;</div><div class="line">            status: 0,</div><div class="line">            message: &apos;保存失败&apos;</div><div class="line">        &#125;</div><div class="line">        appResponse(res, JSON.stringify(resultObj))</div><div class="line">    &#125;)</div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<h4 id="数据库操作-1"><a href="#数据库操作-1" class="headerlink" title="数据库操作"></a>数据库操作</h4><p>由于数据库连接采用相同的配置，此处省略数据库连接的代码。</p>
<p>由于图片会被编码成base64格式的数据，考虑到content字段的数据量会比较大，在设计content字段时采用的是longtext类型。</p>
<p>根据实际的业务逻辑，在写完一篇文章后会直接展示该篇文章，所以在将一篇文章保存后会获取该文章的id返回给客户端，因此以下代码中使用了Promise链的写法</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div></pre></td><td class="code"><pre><div class="line">// 保存文章</div><div class="line">articleDbUtil.saveArticle = function (article) &#123;</div><div class="line">    var promise = new Promise(function (resolve, reject) &#123;</div><div class="line">        connection.connect(function () &#123;</div><div class="line">            var sql = &apos;insert into article(user_id, title, content, publish_time) values(?, ?, ?, ?)&apos;</div><div class="line">            var params = [article.userId, article.title, article.content, article.publishTime]</div><div class="line">            connection.query(sql, params, function (error, response) &#123;</div><div class="line">                if(error) &#123;</div><div class="line">                    reject(error)</div><div class="line">                &#125; else &#123;</div><div class="line">                    resolve(response)</div><div class="line">                &#125;</div><div class="line">            &#125;)</div><div class="line">        &#125;)</div><div class="line">    &#125;)</div><div class="line">    var newPromise = promise.then(function () &#123;</div><div class="line">        return new Promise(function (resolve, reject) &#123;</div><div class="line">            connection.connect(function () &#123;</div><div class="line">                var sql = &apos;select id from article where user_id = ? and title = ? and publish_time = ?&apos;</div><div class="line">                var params = [article.userId, article.title, article.publishTime]</div><div class="line">                connection.query(sql, params, function (error, response) &#123;</div><div class="line">                    if (error) &#123;</div><div class="line">                        reject(error)</div><div class="line">                    &#125; else &#123;</div><div class="line">                        resolve(response)</div><div class="line">                    &#125;</div><div class="line">                &#125;)</div><div class="line">            &#125;)</div><div class="line">        &#125;)</div><div class="line">    &#125;)</div><div class="line"></div><div class="line">    return newPromise</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h4 id="处理响应"><a href="#处理响应" class="headerlink" title="处理响应"></a>处理响应</h4><p>在保存完文章后，会根据返回的文章id，再跳转到文章展示的页面，所以会用<code>_self.$router.push(&#39;/article/&#39; + resData.articleId)</code>进行路由跳转</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line">// 保存文章</div><div class="line">saveArticle () &#123;</div><div class="line">    this.$http.post(&apos;/article/saveArticle&apos;, this.note).then(function (response) &#123;</div><div class="line">        var resData = JSON.parse(response.body)</div><div class="line">        if (resData.status) &#123;</div><div class="line">            var _self = this</div><div class="line">            _self.resMsg = &apos;恭喜你!发表成功&apos;</div><div class="line">            _self.show_result = true</div><div class="line">            setTimeout(function () &#123;</div><div class="line">                _self.$router.push(&apos;/article/&apos; + resData.articleId)</div><div class="line">            &#125;, 1000)</div><div class="line">        &#125; else &#123;</div><div class="line">            this.show_result = true</div><div class="line">            this.resMsg = &apos;发表失败&apos;</div><div class="line">        &#125;</div><div class="line">    &#125;)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="文章列表"><a href="#文章列表" class="headerlink" title="文章列表"></a>文章列表</h3><p>在写完文章后，会在主页上显示出已经写的文章列表，如下图显示<br><img src="https://p0.meituan.net/dpnewvc/16943ad2e51e5b7f9b8cd159c5cb9dbd1472821.png"></p>
<h4 id="前端页面内容-2"><a href="#前端页面内容-2" class="headerlink" title="前端页面内容"></a>前端页面内容</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div></pre></td><td class="code"><pre><div class="line">&lt;template&gt;</div><div class="line">    &lt;div&gt;</div><div class="line">        &lt;ul&gt;</div><div class="line">            &lt;li class=&quot;list&quot; v-for=&quot;article in articles&quot;&gt;</div><div class="line">                &lt;p class=&quot;list-top&quot;&gt;</div><div class="line">                    &lt;a href=&quot;#&quot; class=&quot;author&quot;&gt;</div><div class="line">                        &lt;span&gt;&#123;&#123;article.nickname&#125;&#125;&lt;/span&gt;</div><div class="line">                    &lt;/a&gt;</div><div class="line">                    &lt;span class=&quot;time&quot;&gt;</div><div class="line">                        - &#123;&#123;article.publish_time&#125;&#125;</div><div class="line">                    &lt;/span&gt;</div><div class="line">                &lt;/p&gt;</div><div class="line">                &lt;h2 class=&quot;title&quot;&gt;</div><div class="line">                    &lt;router-link :to=&quot;&#123;path: &apos;/article/&apos; + article.id&#125;&quot;&gt;&#123;&#123;article.title&#125;&#125;&lt;/router-link&gt;</div><div class="line">                &lt;/h2&gt;</div><div class="line">                &lt;span class=&quot;small-text&quot;&gt;阅读 &#123;&#123;article.read_count&#125;&#125;&lt;/span&gt;</div><div class="line">                &lt;span class=&quot;small-text&quot;&gt;评论 &#123;&#123;article.comment_count&#125;&#125;&lt;/span&gt;</div><div class="line">                &lt;span class=&quot;small-text&quot;&gt;喜欢 &#123;&#123;article.like_count&#125;&#125;&lt;/span&gt;</div><div class="line">                &lt;span class=&quot;small-text&quot;&gt;打赏 &#123;&#123;article.reward_count&#125;&#125;&lt;/span&gt;</div><div class="line">                &lt;span class=&quot;image&quot;</div><div class="line">                      :style=&quot;&#123;&apos;background&apos;: &apos;url(&apos; + (article.picture_url || defaultUrl) + &apos;)&apos;, backgroundSize: &apos;100%&apos;, backgroundRepeat: &apos;no-repeat&apos; &#125;&quot;&gt;&lt;/span&gt;</div><div class="line">            &lt;/li&gt;</div><div class="line">        &lt;/ul&gt;</div><div class="line">    &lt;/div&gt;</div><div class="line">&lt;/template&gt;</div></pre></td></tr></table></figure>
<h4 id="加载文章列表"><a href="#加载文章列表" class="headerlink" title="加载文章列表"></a>加载文章列表</h4><p>在刚进入主页的时候会在主页Home.vue文件中发送请求，加载出文章列表</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">methods: &#123;</div><div class="line">    displayArticles (type) &#123;</div><div class="line">        // 发送请求,找出对应类型的文章</div><div class="line">        var url = &apos;/article/list?type=&apos; + type</div><div class="line">        this.$http.get(url).then(function (response) &#123;</div><div class="line">            </div><div class="line">        &#125;)</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h4 id="服务端请求"><a href="#服务端请求" class="headerlink" title="服务端请求"></a>服务端请求</h4><p>在app-article-server.js文件中，包含了加载文件列表的内容</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line">// 加载文章列表</div><div class="line">app.get(&apos;/article/list&apos;, function (req, res) &#123;</div><div class="line">    var type = req.query.type</div><div class="line">    articleDbUtil.loadArticleByType(type).then(function (response) &#123;</div><div class="line">        if(response.length) &#123;</div><div class="line">            var resultObj = &#123;</div><div class="line">                status: 1,</div><div class="line">                message: &apos;加载成功&apos;,</div><div class="line">                articleList: response</div><div class="line">            &#125;</div><div class="line">            appResponse(res, JSON.stringify(resultObj))</div><div class="line">        &#125;</div><div class="line">    &#125;, function () &#123;</div><div class="line">        var resultObj = &#123;</div><div class="line">            status: 0,</div><div class="line">            message: &apos;加载失败&apos;</div><div class="line">        &#125;</div><div class="line">        appResponse(resultObj)</div><div class="line">    &#125;)</div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<h4 id="数据库操作-2"><a href="#数据库操作-2" class="headerlink" title="数据库操作"></a>数据库操作</h4><p>在articleDbUtil.js文件中，包含了从数据库加载出文章列表的内容</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line">// 加载某类型的文章</div><div class="line">articleDbUtil.loadArticleByType = function (type) &#123;</div><div class="line">    var promise = new Promise(function (resolve, reject) &#123;</div><div class="line">        connection.connect(function () &#123;</div><div class="line">            var sql = &apos;select a.*, u.nickname from article as a, users as u where a.user_id = u.id&apos;</div><div class="line">            var params = []</div><div class="line">            connection.query(sql, function (error, response) &#123;</div><div class="line">                if (error) &#123;</div><div class="line">                    reject(error)</div><div class="line">                &#125; else &#123;</div><div class="line">                    resolve(response)</div><div class="line">                &#125;</div><div class="line">            &#125;)</div><div class="line">        &#125;)</div><div class="line">    &#125;)</div><div class="line">    return promise</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h4 id="处理响应-1"><a href="#处理响应-1" class="headerlink" title="处理响应"></a>处理响应</h4><p>在将文章列表返回给浏览器端后，会直接将数据写到Vuex的store中，在ArticleList.vue文件中直接从store中读取即可。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line">displayArticles (type) &#123;</div><div class="line">    // 发送请求,找出对应类型的文章</div><div class="line">    var url = &apos;/article/list?type=&apos; + type</div><div class="line">    this.$http.get(url).then(function (response) &#123;</div><div class="line">        var resData = JSON.parse(response.body)</div><div class="line">        if (resData.status) &#123;</div><div class="line">            var articleList = resData.articleList</div><div class="line">            var payload = &#123;</div><div class="line">                type: type,</div><div class="line">                articleList: articleList</div><div class="line">            &#125;</div><div class="line">            this.$store.dispatch(&apos;displayArticles&apos;, payload)</div><div class="line">        &#125;</div><div class="line">    &#125;)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>至此关于注册登录和写文章以及加载文章列表的功能就已经完成了，这基本上是简书网站的最主要功能了，后续的例如专题的功能可以按照以上的5个步骤来完成，当然如果你们能想到哪些更有趣的功能，都可以自己添加到网站上。</p>
<p>通过两篇文章，基本涵盖了利用Vue全家桶+Express+Webpack搭建简书的全过程，包括前端、后台、数据库操作等等，希望能给大家带来帮助，也希望大家能提些意见。</p>
<h3 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h3><ul>
<li><a href="http://javascript.ruanyifeng.com/nodejs/express.html#toc0" target="_blank" rel="external">Express框架</a></li>
<li><a href="http://www.cnblogs.com/keepfool/p/5657065.html" target="_blank" rel="external">Vue-resource全攻略</a></li>
<li><a href="https://github.com/surmon-china/vue-quill-editor" target="_blank" rel="external">Vue富文本编辑器vue-quill-editor</a></li>
<li><a href="http://blog.csdn.net/xycit/article/details/5854694" target="_blank" rel="external">Mysql基本操作</a></li>
</ul>
</span>
      
    </div>

    <footer class="post-footer">

      
        <div class="post-nav">
          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/03/03/wangweitao/AliActivityRouter/" rel="prev">ActivityRouter</a>
            
          </div>

          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/02/24/zhiqin/RxJava_zip_Observable_carefully/" rel="next">RxJava 谨慎串联Observable</a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
  <a class="jiathis_button_tsina"></a>
  <a class="jiathis_button_tqq"></a>
  <a class="jiathis_button_weixin"></a>
  <a class="jiathis_button_cqq"></a>
  <a class="jiathis_button_douban"></a>
  <a class="jiathis_button_renren"></a>
  <a class="jiathis_button_qzone"></a>
  <a class="jiathis_button_kaixin001"></a>
  <a class="jiathis_button_copy"></a>
  <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
  <a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
  var jiathis_config={
    hideMore:false
  }
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>

 </div>

        

        
          <div class="comments" id="comments">
            <div id="SOHUCS" sid="" ></div>
          </div>
        
      </div>

      
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <a href="https://github.com/xgfe" target="_blank"><img class="site-author-image" src="http://p0.meituan.net/xgfe/082a9624ba5ae8602150a2d43968463e49348.png" alt="xgfe" itemprop="image"/></a>
          <p class="site-author-name" itemprop="name">xgfe</p>
        </div>
        <p class="site-description motion-element" itemprop="description">xgfe's blog. 鲜果前端的技术博客，鲜果前端研发部官方博客。前端基础技术研究：html, html5, javascript, css, css3；前端框架研究：angularJs, react, react native.</p>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">89</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          <div class="site-state-item site-state-categories">
            
              <span class="site-state-item-count">37</span>
              <span class="site-state-item-name">作者</span>
              
          </div>

          <div class="site-state-item site-state-tags">
            <a href="/tags">
              <span class="site-state-item-count">131</span>
              <span class="site-state-item-name">标签</span>
              </a>
          </div>

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" target="_blank" rel="alternate">
              <i class="menu-item-icon icon-next-feed"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/xgfe" target="_blank">GitHub</a>
              </span>
            
          
        </div>

        
        

        <div class="links-of-author motion-element">
          
        </div>

      </section>

      
        <section class="post-toc-wrap sidebar-panel-active">
          <div class="post-toc-indicator-top post-toc-indicator"></div>
          <div class="post-toc">
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#准备知识"><span class="nav-number">2.</span> <span class="nav-text">准备知识</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数据库设计"><span class="nav-number">3.</span> <span class="nav-text">数据库设计</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#创建server"><span class="nav-number">4.</span> <span class="nav-text">创建server</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#注册与登录"><span class="nav-number">5.</span> <span class="nav-text">注册与登录</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#前端页面内容"><span class="nav-number">5.1.</span> <span class="nav-text">前端页面内容</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#vue-resource发送请求"><span class="nav-number">5.2.</span> <span class="nav-text">vue-resource发送请求</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#服务端接收请求"><span class="nav-number">5.3.</span> <span class="nav-text">服务端接收请求</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#数据库操作"><span class="nav-number">5.4.</span> <span class="nav-text">数据库操作</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#写文章"><span class="nav-number">6.</span> <span class="nav-text">写文章</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#前端页面内容-1"><span class="nav-number">6.1.</span> <span class="nav-text">前端页面内容</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Vue-resource发送请求"><span class="nav-number">6.2.</span> <span class="nav-text">Vue-resource发送请求</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#服务端处理请求"><span class="nav-number">6.3.</span> <span class="nav-text">服务端处理请求</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#数据库操作-1"><span class="nav-number">6.4.</span> <span class="nav-text">数据库操作</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#处理响应"><span class="nav-number">6.5.</span> <span class="nav-text">处理响应</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#文章列表"><span class="nav-number">7.</span> <span class="nav-text">文章列表</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#前端页面内容-2"><span class="nav-number">7.1.</span> <span class="nav-text">前端页面内容</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#加载文章列表"><span class="nav-number">7.2.</span> <span class="nav-text">加载文章列表</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#服务端请求"><span class="nav-number">7.3.</span> <span class="nav-text">服务端请求</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#数据库操作-2"><span class="nav-number">7.4.</span> <span class="nav-text">数据库操作</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#处理响应-1"><span class="nav-number">7.5.</span> <span class="nav-text">处理响应</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参考资料"><span class="nav-number">8.</span> <span class="nav-text">参考资料</span></a></li></ol></div>
            
          </div>
          <div class="post-toc-indicator-bottom post-toc-indicator"></div>
        </section>
      

    </div>
  </aside>


    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner"> <div class="copyright" >
  
  &copy; &nbsp; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="icon-next-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xgfe</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" target="_blank" href="http://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


 </div>
    </footer>

    <div class="back-to-top"></div>
  </div>

  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  
  
    <script type="text/javascript"> 
(function(){ 
var appid = 'cysWiXvkm'; 
var conf = 'prod_fc970dbe85103c7a79b2c4f3dc7fb190'; 
var width = window.innerWidth || document.documentElement.clientWidth; 
if (width < 960) { 
window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="http://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("http://changyan.sohu.com/upload/changyan.js",function(){window.changyan.api.config({appid:appid,conf:conf})}); } })(); </script>
    

  


  
  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js"></script>
  <script type="text/javascript" src="/js/fancy-box.js?v=0.4.5.1"></script>


  <script type="text/javascript" src="/js/helpers.js?v=0.4.5.1"></script>
  

  <script type="text/javascript" src="/vendors/velocity/velocity.min.js"></script>
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js"></script>

  <script type="text/javascript" src="/js/motion_global.js?v=0.4.5.1" id="motion.global"></script>




  <script type="text/javascript" src="/js/nav-toggle.js?v=0.4.5.1"></script>
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  
<script type="text/javascript" src="/js/bootstrap.scrollspy.js?v=0.4.5.1" id="bootstrap.scrollspy.custom"></script>


<script type="text/javascript" id="sidebar.toc.highlight">
  $(document).ready(function () {
    var tocSelector = '.post-toc';
    var $tocSelector = $(tocSelector);
    var activeCurrentSelector = '.active-current';

    $tocSelector
      .on('activate.bs.scrollspy', function () {
        var $currentActiveElement = $(tocSelector + ' .active').last();

        removeCurrentActiveClass();
        $currentActiveElement.addClass('active-current');

        $tocSelector[0].scrollTop = $currentActiveElement.position().top;
      })
      .on('clear.bs.scrollspy', function () {
        removeCurrentActiveClass();
      });

    function removeCurrentActiveClass () {
      $(tocSelector + ' ' + activeCurrentSelector)
        .removeClass(activeCurrentSelector.substring(1));
    }

    function processTOC () {
      getTOCMaxHeight();
      toggleTOCOverflowIndicators();
    }

    function getTOCMaxHeight () {
      var height = $('.sidebar').height() -
                   $tocSelector.position().top -
                   $('.post-toc-indicator-bottom').height();

      $tocSelector.css('height', height);

      return height;
    }

    function toggleTOCOverflowIndicators () {
      tocOverflowIndicator(
        '.post-toc-indicator-top',
        $tocSelector.scrollTop() > 0 ? 'show' : 'hide'
      );

      tocOverflowIndicator(
        '.post-toc-indicator-bottom',
        $tocSelector.scrollTop() >= $tocSelector.find('ol').height() - $tocSelector.height() ? 'hide' : 'show'
      )
    }

    $(document).on('sidebar.motion.complete', function () {
      processTOC();
    });

    $('body').scrollspy({ target: tocSelector });
    $(window).on('resize', function () {
      if ( $('.sidebar').hasClass('sidebar-active') ) {
        processTOC();
      }
    });

    onScroll($tocSelector);

    function onScroll (element) {
      element.on('mousewheel DOMMouseScroll', function (event) {
          var oe = event.originalEvent;
          var delta = oe.wheelDelta || -oe.detail;

          this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
          event.preventDefault();

          toggleTOCOverflowIndicators();
      });
    }

    function tocOverflowIndicator (indicator, action) {
      var $indicator = $(indicator);
      var opacity = action === 'show' ? 0.4 : 0;
      $indicator.velocity ?
        $indicator.velocity('stop').velocity({
          opacity: opacity
        }, { duration: 100 }) :
        $indicator.stop().animate({
          opacity: opacity
        }, 100);
    }

  });
</script>

<script type="text/javascript" id="sidebar.nav">
  $(document).ready(function () {
    var html = $('html');
    var TAB_ANIMATE_DURATION = 200;
    var hasVelocity = $.isFunction(html.velocity);

    $('.sidebar-nav li').on('click', function () {
      var item = $(this);
      var activeTabClassName = 'sidebar-nav-active';
      var activePanelClassName = 'sidebar-panel-active';
      if (item.hasClass(activeTabClassName)) {
        return;
      }

      var currentTarget = $('.' + activePanelClassName);
      var target = $('.' + item.data('target'));

      hasVelocity ?
        currentTarget.velocity('transition.slideUpOut', TAB_ANIMATE_DURATION, function () {
          target
            .velocity('stop')
            .velocity('transition.slideDownIn', TAB_ANIMATE_DURATION)
            .addClass(activePanelClassName);
        }) :
        currentTarget.animate({ opacity: 0 }, TAB_ANIMATE_DURATION, function () {
          currentTarget.hide();
          target
            .stop()
            .css({'opacity': 0, 'display': 'block'})
            .animate({ opacity: 1 }, TAB_ANIMATE_DURATION, function () {
              currentTarget.removeClass(activePanelClassName);
              target.addClass(activePanelClassName);
            });
        });

      item.siblings().removeClass(activeTabClassName);
      item.addClass(activeTabClassName);
    });

    $('.post-toc a').on('click', function (e) {
      e.preventDefault();
      var targetSelector = escapeSelector(this.getAttribute('href'));
      var offset = $(targetSelector).offset().top;
      hasVelocity ?
        html.velocity('stop').velocity('scroll', {
          offset: offset  + 'px',
          mobileHA: false
        }) :
        $('html, body').stop().animate({
          scrollTop: offset
        }, 500);
    });

    // Expand sidebar on post detail page by default, when post has a toc.
    var $tocContent = $('.post-toc-content');
    if (isDesktop() && CONFIG.sidebar === 'post') {
      if ($tocContent.length > 0 && $tocContent.html().trim().length > 0) {
        displaySidebar();
      }
    }
  });
</script>



  <script type="text/javascript">
    $(document).ready(function () {
      if (CONFIG.sidebar === 'always') {
        displaySidebar();
      }
      if (isMobile()) {
        FastClick.attach(document.body);
      }
    });
  </script>

  

  
  

  
  <script type="text/javascript" src="/js/lazyload.js"></script>
  <script type="text/javascript">
    $(function () {
      $("#posts").find('img').lazyload({
        placeholder: "/images/loading.gif",
        effect: "fadeIn"
      });
    });
  </script>

  <!-- google search, added by felix -->
  <script>
      $('#gg-form').on('submit', function(e) {
        var keyword = $.trim($(this).find('#gg-search-input').val());
        if (keyword) {
          location.href = 'https://www.google.com.hk/?gfe_rd=cr&ei=hXw8VpjtHuLC8AeSuIjQAg&gws_rd=ssl#safe=strict&q='+encodeURIComponent(keyword)+'+site:xgfe.github.io';
        }
        return false;
      });
  </script>
  <!-- baidu 站长自动推送 -->
  <script>
  (function(){
      var bp = document.createElement('script');
      bp.src = '//push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
  })();
  </script>
</body>
</html>
